require('dotenv').config();
const mongoose = require('mongoose');
const User = require('../models/User');

const testUsers = [
  {
    username: 'admin',
    email: 'admin@example.com',
    password: 'admin123',
    role: 'admin',
    department: '系统管理部'
  },
  {
    username: 'manager',
    email: 'manager@example.com',
    password: 'manager123',
    role: 'manager',
    department: '运营管理部'
  }
];

async function seedUsers() {
  try {
    // 优先使用环境变量中的数据库连接字符串
    const mongoUri = process.env.MONGODB_URI || 'mongodb+srv://gzhukun:gzk135246@cluster0.pnlj5a1.mongodb.net/smartpark';
    await mongoose.connect(mongoUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('数据库连接成功');
    
    // 清空现有用户数据
    await User.deleteMany({});
    console.log('清空现有用户数据');
    
    // 插入测试用户
    for (const userData of testUsers) {
      const user = new User(userData);
      await user.save();
      console.log(`创建用户: ${userData.username} (${userData.email})`);
    }
    
    console.log(`成功创建 ${testUsers.length} 个用户`);
    
    process.exit(0);
  } catch (error) {
    console.error('创建用户数据失败:', error);
    process.exit(1);
  }
}

seedUsers();